package com.catsic.practice.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.catsic.practice.entity.LeaveApplication;
import com.catsic.practice.entity.Result;
import com.catsic.practice.entity.TaskDTO;
import com.catsic.practice.mapper.LeaveApplicationMapper;
import com.catsic.practice.service.LeaveProcessService;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

/**
 * @Author: zhangzf
 * @CreateTime: 2025-10-24  15:26
 * @Description: 请假流程控制器
 */
@RestController
@RequestMapping("/leave")
public class LeaveProcessController {

    @Autowired
    private LeaveProcessService leaveProcessService;

    @Autowired
    private LeaveApplicationMapper leaveApplicationMapper;

    /**
     * 提交请假申请
     */
    @PostMapping("/apply")
    public Result applyLeave(@RequestBody LeaveApplication leaveApplication){
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        leaveApplication.setId(uuid);
        Result applyResult = leaveProcessService.startLeaveProcess(leaveApplication);
        String processInstanceId = String.valueOf(applyResult.getData());
        leaveApplication.setProcessInstanceId(processInstanceId);
        leaveApplicationMapper.insert(leaveApplication);
        return Result.success("提交成功");
    }

    /**
     * 获取用户待办任务
     */
    @GetMapping("/tasks/{assignee}")
    public Result getUserTasks(@PathVariable String assignee){
        List<TaskDTO> taskList = leaveProcessService.getUserTasks(assignee);
        return Result.success(taskList);
    }

    /**
     * 审批任务
     */
    @PostMapping("/approve/{taskId}")
    public Result approveLeave(@PathVariable String taskId,@RequestBody Map<String, Object> request) {
        String decision = (String) request.get("decision");
        String comment = (String) request.get("comment");
        String nextAssignee = (String) request.get("nextAssignee");
        leaveProcessService.completeTask(taskId, decision, comment, nextAssignee);
        return Result.success("审批成功");
    }

    /**
     * 获取流程状态
     */
    @GetMapping("/status/{processInstanceId}")
    public Result getLeaveStatus(@PathVariable String processInstanceId){
        Result  resultStatus = leaveProcessService.getProcessStatus(processInstanceId);
        String status = (String) resultStatus.getData();
        //更新请假流程状态
        UpdateWrapper<LeaveApplication> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("process_instance_id", processInstanceId);
        updateWrapper.set("status", status);
        leaveApplicationMapper.update(null, updateWrapper);
        return Result.success(status);
    }
}
